package com.example.hzcccc.weather;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AlphabetIndexer;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hzcccc on 2016/3/18.
 */
public class ManagerActivity extends AppCompatActivity {
    MotionEvent event;

    private TextView float_letter;
    private Cursor cursor;
    private LinearLayout titleLayout;
    private TextView title;
    private ListView contactsListview;
    private ContactAdapter adapter;
    private AlphabetIndexer indexer;
    private List<Contact> contacts = new ArrayList<Contact>();
    private String alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private int lastFirstVisiableItem = -1;
    SearchView mSearchView;
    SQLdm s = new SQLdm();
    SQLiteDatabase db;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manager);

        adapter = new ContactAdapter(ManagerActivity.this, R.layout.contact_item, contacts);
        titleLayout = (LinearLayout) findViewById(R.id.title_layout);
        title = (TextView) findViewById(R.id.title);
        contactsListview = (ListView) findViewById(R.id.contacts_listview);
        float_letter = (TextView) findViewById(R.id.float_letter);
        Toolbar toolbar = (Toolbar) findViewById(R.id.id_manager_toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();

        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);
        db = s.openDatabase(ManagerActivity.this);
        cursor = db.rawQuery("SELECT * FROM cities ORDER BY key ASC", null);
        initDatabase(cursor);


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String val;
                Bundle data;
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0x11:
                        data = msg.getData();
                        val = data.getString("value");
                        cursor = db.rawQuery("SELECT * FROM cities WHERE name LIKE '%" + val + "%' ORDER BY key ASC", null);

                        if (cursor.getCount() == 0) {
                            //无结果时的操作
                        } else {
                            initDatabase(cursor);
                            adapter.notifyDataSetChanged();
                        }
                        break;
                    case 0x12:
                        data = msg.getData();
                        //updatedatabase(data);
                        break;
                }

            }
        };

        initOnclick();
        contactsListview.setFastScrollAlwaysVisible(true);

    }








    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        setSearchMenu(menu);

        return true;
    }

    private void setSearchMenu(Menu menu) {
        final MenuItem item = menu.findItem(R.id.search_contact);

        mSearchView = (SearchView) MenuItemCompat.getActionView(item);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {


                return false;
            }


            @Override
            public boolean onQueryTextChange(String newText) {
                //Toast.makeText(ManagerActivity.this,"changed",Toast.LENGTH_LONG).show();
                search(newText);

                return false;
            }

            private void search(final String query) {
                //模糊查询
                //cursor = db.rawQuery("SELECT * FROM cities WHERE name LIKE '%"+ query+"%' ORDER BY key ASC",null);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("value", query);
                        msg.setData(bundle);
                        msg.what = 0x11;
                        handler.sendMessage(msg);
                    }
                }).start();
            }
        });
    }

    private void initOnclick() {
        contactsListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,final int position, long id) {
                new AlertDialog.Builder(ManagerActivity.this).setTitle(null)
                        .setMessage("是否添加该城市").setNegativeButton("no",null)
                        .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                addcity(position);
                            }
                        }).show();



            }

            private void addcity(int position) {
                SQLdm s = new SQLdm();
                SQLiteDatabase db = s.openDatabase(getApplicationContext());


                // Cursor cursor = db.query("cities",null,null,null,null,null,null);
                Cursor cursor = db.rawQuery("SELECT * FROM cities ORDER BY key ASC", null);
                cursor.move(position + 1);
                final String name = cursor.getString(0);
                final String key = cursor.getString(1);
                String code = cursor.getString(5);
                cursor.close();
                cursor = db.rawQuery("SELECT * FROM managercity WHERE name = '" + name + "'", null);
                if (cursor.getCount() == 0) {
                    ContentValues cv = new ContentValues();
                    cv.put("name", name);
                    cv.put("key", key);
                    cv.put("code", code);
                    db.insert("managercity", null, cv);
                } else {
                    Toast.makeText(ManagerActivity.this, name + "已添加过了", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initDatabase(Cursor cursor) {


//每次初始化listview先清除原来有的数据
        contacts.clear();
        // Cursor cursor = db.query("cities",null,null,null,null,null,null);

        if (cursor.moveToFirst()) {
            do {

                Contact contact = new Contact();

                String name = cursor.getString(0);
                String sortKey = getSortKey(cursor.getString(1));
                contact.setName(name);
                contact.setsorKey(sortKey);
                contacts.add(contact);
            } while (cursor.moveToNext());
        }
        startManagingCursor(cursor);
        indexer = new AlphabetIndexer(cursor, 1, alphabet);
        adapter.setmIndexer(indexer);

        if (contacts.size() > 0) {
            setupContactsListView();
        }


    }

    private void setupContactsListView() {
        contactsListview.setAdapter(adapter);
        contactsListview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

                switch (scrollState) {
                    //静止状态
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        float_letter.setVisibility(View.GONE);
                        break;
                    //手指滚动状态
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        float_letter.setVisibility(View.VISIBLE);
                        break;
                    //手指不动了，但是屏幕还在滚动状态
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                        float_letter.setVisibility(View.VISIBLE);
                        break;

                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int section = indexer.getSectionForPosition(firstVisibleItem);
                int nextSecPosition = indexer.getPositionForSection(section + 1);

                if (firstVisibleItem != lastFirstVisiableItem) {
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout.getLayoutParams();
                    params.topMargin = 0;
                    titleLayout.setLayoutParams(params);
                    title.setText(String.valueOf(alphabet.charAt(section)));
                    float_letter.setText(String.valueOf(alphabet.charAt(section)));

                }

                if (nextSecPosition == firstVisibleItem + 1) {
                    View childView = view.getChildAt(0);
                    if (childView != null) {
                        int titleHeight = titleLayout.getHeight();
                        int bottom = childView.getBottom();
                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
                                .getLayoutParams();
                        if (bottom < titleHeight) {
                            float pushedDistance = bottom - titleHeight;
                            params.topMargin = (int) pushedDistance;
                            titleLayout.setLayoutParams(params);
                        } else {
                            if (params.topMargin != 0) {
                                params.topMargin = 0;
                                titleLayout.setLayoutParams(params);
                            }
                        }
                    }
                }
                lastFirstVisiableItem = firstVisibleItem;
            }
        });

    }

    private String getSortKey(String sortKeyString) {
        String key = sortKeyString.substring(0, 1).toUpperCase();
        if (key.matches("[A-Z]")) {
            return key;
        }
        return "#";
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                ManagerActivity.this.finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


}
